package com.cblz.bd.server.core.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cblz.bd.common.core.entity.BaAdminLog;
import com.cblz.bd.common.core.entity.system.QueryRequest;
import com.cblz.bd.common.core.utils.ResultResponse;
import com.cblz.bd.common.core.utils.SearchParamsUtil;
import com.cblz.bd.server.core.annotation.AdminApiController;
import com.cblz.bd.server.core.service.BaAdminLogService;
import io.vavr.Tuple4;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * {@code @Name:} BaAdminLogController
 * {@code @Description: } 日志管理控制层
 * {@code @Author:} by yanjieping
 * {@code @CreateDate:} 2022/11/14 - 周一
 */
@Slf4j
@AdminApiController("log/admin")
@RequiredArgsConstructor
public class BaAdminLogController {

    private final BaAdminLogService baAdminLogService;

    /**
     * 查询
     *
     * @param searchParams 包含通用查询条件和分页参数
     *                     例： search[]: {"field":"id","val":"1","operator":"LIKE"}
     *                     page: 1
     * @return
     * @throws Exception
     */
    @PostMapping("index")
    public ResultResponse list(@RequestBody Map<String, Object> searchParams) throws Exception {
        var queryRequest = new QueryRequest();

        Tuple4 paramsHandle = SearchParamsUtil.searchParamsHandle(searchParams);
        var search = (List<LinkedHashMap<String, Object>>) paramsHandle._1;
        var page = paramsHandle._2;
        var limit = paramsHandle._3;
        var quickSearch = (Map<String, String>) paramsHandle._4;

        if (page != null) queryRequest.setPageNum(Integer.parseInt(page.toString()));
        if (limit != null) queryRequest.setPageSize(Integer.parseInt(limit.toString()));

        BaAdminLog baAdminLog = SearchParamsUtil.ParamsFormat2Class(new BaAdminLog(), search, quickSearch);
        IPage<BaAdminLog> iPage = baAdminLogService.getAllLog(baAdminLog, queryRequest);
        if (iPage == null) return new ResultResponse().data("");

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", iPage.getRecords().isEmpty() ? null : iPage.getRecords());
        resultMap.put("total", iPage.getTotal());
        return new ResultResponse().data(resultMap);
    }
}
